package com.starhub.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.starhub.web.model.ProductCarousel;
import com.starhub.web.model.Tile;

@Controller
public class MobileController extends StarHubBaseController {
	
	@RequestMapping(value = "/mobile.html")
	public ModelAndView viewMobilePage(@RequestParam(value = "isAdmin", required = false, defaultValue = "false") Boolean isAdmin, 
			final HttpServletRequest httpServletRequest, final ModelMap model) {
		
		getCommonModel(httpServletRequest, model);
		
		model.addAttribute("isAdmin", isAdmin);
		
		return new ModelAndView("personal/mobile/mobileMainPage", model);
	}
	
	@RequestMapping(value = "/getProductCarousels.html")
	public ModelAndView getMobileProductCarousel(@RequestParam(value = "categoryId") int categoryId,
			@RequestParam(value = "isAdmin") boolean isAdmin, final ModelMap model) {
		
		List<ProductCarousel> productCarousels = productHost.getProductCarousels(categoryId);
		model.addAttribute("productCarousels", productCarousels);
		model.addAttribute("isAdmin", isAdmin);
		
		return new ModelAndView("common/productCarousel", model);
	}
	
	@RequestMapping(value = "/getTiles.html")
	public ModelAndView getMobileTile(@RequestParam(value = "categoryId") int categoryId,
			@RequestParam(value = "isAdmin") boolean isAdmin, final ModelMap model) {
		List<Tile> tiles = tileHost.getTiles(categoryId);
		
		List<Tile> existingCustomerTiles = extractTile(tiles, "existing");
		List<Tile> newCustomerTiles = extractTile(tiles, "new");
		
		model.addAttribute("existingCustomerTiles", existingCustomerTiles);
		model.addAttribute("newCustomerTiles", newCustomerTiles);
		model.addAttribute("isAdmin", isAdmin);
		
		return new ModelAndView("common/tiles", model);
	}
	
	private List<Tile> extractTile(List<Tile> tiles, String type) {
		List<Tile> extracedTiles = new ArrayList<Tile>();
		
		for (Tile tile : tiles) {
			if (type.equals(tile.getCustomerType()) || "both".equals(tile.getCustomerType())) {
				extracedTiles.add(tile);
			}
		}
		
		return extracedTiles;
	}
}
